<template>
	<view class="box" style="display: none;" >
		<!-- 步骤条 -->
		<view class="AiImaga">
			<cc-horSteps title=" " colors="#FF9900" :stepData="stepData" />
		</view>

		<!-- 二级分类选择 -->
		<view class="category-wrapper">
			<view class="category-box">
				<view v-for="(item, index) in parentCategories" f :key="index" class="category-item"
					:class="{ active: selectedParentIndex === index }" @click="selectParent(index,item)">
					{{ item.name }}
				</view>
			</view>

			<view class="subcategory-box">
				<view v-for="(sub, subIndex) in parentCategories[selectedParentIndex].items" :key="subIndex"
					class="subcategory-item" :class="{ active: selectedSubIndex === subIndex }"
					@click="selectSub(subIndex,sub)">
					{{ sub.name }}
				</view>
			</view>
		</view>

		<!-- 图片上传 -->
		<view class="AiImag">
			<view class="AiImag-typea">
				<view class="AiImag-type" v-for="(item,index) in selectAiType" :key="index" >
					<view>{{item}}</view>
				</view>
			</view>
			<l-upload uploadType="img" :limit="1" @complete="onUploadComplete" ref="childRef" />
		</view>

		<!-- 操作按钮 -->
		<view class="titlebia">
			<view class="titlebia1" @click="handleGenerate">AI生成</view>
			<view class="titlebia2" @click="checkTaskStatus">更新状态</view>
		</view>

		<!-- 生成图片展示 -->
		<view class="image-grid">
			<view class="image-item" v-for="(img, index) in imageList" :key="index">
				<image :src="img.url" mode="aspectFill" />
			</view>
		</view>
	</view>
</template>

<script>
	import api from "../../api/Channel.js";
	import commonMixin from "@/mixins/qiLiuyun.js";
	import request from '../../api/index.js';
	import suffixAddress from '../../api/suffixAddress.js'
	export default {
		mixins: [commonMixin],
		data() {
			return {
				stepData: [{
						step_id: 1,
						name: "待处理",
						isNow: 0,
						type: 0
					},
					{
						step_id: 2,
						name: "生成中",
						isNow: 0,
						type: 0
					},
					{
						step_id: 3,
						name: "成功",
						isNow: 0,
						type: 0
					},
					{
						step_id: 4,
						name: "失败",
						isNow: 0,
						type: 0
					},
				],
				imagArr: [],
				Aikey: null,
				imageList: [],
				parentCategories: [],
				selectedParentIndex: 0,
				selectedSubIndex: -1,
				selectAiType: [],
				selectUnpdata: [],
				quanx:false
			};
		},
		async onLoad() {
			const list = await this.getCategoryList();
			this.parentCategories = list.data;
		},
		onShow() {
			
		},
		methods: {
			getCategoryList(params = {}) {
				return new Promise((resolve, reject) => {
					let obj = {
						url: api.Channel + suffixAddress.add().categories,
						method: 'GET',
						data: params,
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
					}
					let resa = request(obj)
					resolve(resa)
				});
			},
			selectParent(index, item) {
				this.selectedParentIndex = index;
			},
			selectSub(index, item) {
				this.selectedSubIndex = index;
				this.selectAiType[this.selectedParentIndex] = item.name
				this.selectUnpdata[this.selectedParentIndex] = item.id
				for (let i = 0; i < this.selectAiType.length; i++) {
					if (this.selectAiType[i] == undefined) {
						this.selectAiType[i] = ''
					}
				}
			},
			onUploadComplete(e) {
				wx.cropImage({
					src: e.imageArr[0],
					cropScale: "1:1",
					success: (cropRes) => {
						this.imagArr = [cropRes.tempFilePath];
						console.log("裁剪后的图片路径:", cropRes.tempFilePath);
					},
					fail: (err) => {
						console.error("裁剪失败:", err);
					},
				});
			},
			handleGenerate() {
				if (!this.imagArr.length) return this.showLoading("请先上传图片", "showToast", "error");
				if (this.stepData[0].type === 1) return this.showLoading("已有任务在生成", "showToast", "error");
				this.createAITask();
				this.imageList = []
			},
			async createAITask() {
				try {
					const key = await this.Tokenqiniu(this.imagArr[0],'ai-generate-ref');
					this.Aikey = await this.generate(key);
					this.checkTaskStatus();
				} catch (error) {
					console.error("任务创建失败:", error);
				}
			},
			generate(key) {
				let th = this
				th.selectUnpdata = th.selectUnpdata.filter(item => item != null); // 同时去掉 empty/null/undefined
				return new Promise((resolve, reject) => {
					let obj = {
						url: api.Channel + suffixAddress.add().generate,
						method: 'POST',
						contentType: 'application/json',
						data: {
							refImg: key,
							categoryItemIdList: th.selectUnpdata,
						},
					}
					let resa = request(obj)
					resolve(resa)
				});
			},
			checkTaskStatus() {
				if (!this.Aikey) return this.showLoading("请先生成", "showToast", "error");
				let obja = {
					url: api.Channel + suffixAddress.add().tasks,
					method: "GET",
					data: {
						taskId: this.Aikey.data.taskId
					},
				}
				let res = request(obja)
				const status = res
				status.then(res => {
					console.log(res.data)
					this.stepData.forEach((item) => (item.type = 0));
					switch (res.data.status) {
						case "PENDING":
							this.stepData[0].type = 1;
							this.showLoading("待处理", "showToast", "success");
							break;
						case "RUNNING":
							this.stepData[0].type = 1;
							this.stepData[1].type = 1;
							this.showLoading("生成中", "showToast", "success");
							break;
						case "SUCCEEDED":
							this.stepData[2].type = 1;
							this.imageList = res.data.imgList || [];
							this.showLoading("成功", "showToast", "success");
							break;
						case "FAILED":
						default:
							this.stepData[3].type = 1;
							this.showLoading("失败", "showToast", "error");
							break;
					}
				})
			},
		},
	};
</script>

<style>
	.box {
		background-color: #f3f4f8;
		width: 100vw;
		min-height: 100vh;
		padding-bottom: 40rpx;
		box-sizing: border-box;
	}

	.AiImaga {
		padding: 20rpx 20rpx 0;
	}

	.category-wrapper {
		margin: 20rpx auto;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
		width: 90%;
	}

	.category-box,
	.subcategory-box {
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
		margin-bottom: 20rpx;
	}

	.category-item,
	.subcategory-item {
		background-color: #f3f4f8;
		margin: 10rpx;
		padding: 16rpx 32rpx;
		border-radius: 40rpx;
		border: 2rpx solid transparent;
		color: #333;
		font-size: 28rpx;
		transition: all 0.3s ease;
	}

	.category-item.active,
	.subcategory-item.active {
		background-color: #ff9900;
		color: #fff;
		border-color: #e68300;
		font-weight: 600;
	}

	.AiImag {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 20rpx;
		padding: 50rpx 0;
		background-color: #fff;
		border-radius: 12rpx;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		height: auto;
	}

	.AiImag-type {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.AiImag-type:first-of-type {
		margin-right: 40rpx;
	}

	.titlebia {
		display: flex;
		justify-content: space-around;
		margin: 0 40rpx 30rpx;
	}

	.titlebia1,
	.titlebia2 {
		flex: 1;
		text-align: center;
		padding: 15rpx 0;
		background: #ff9900;
		border-radius: 25rpx;
		color: #fff;
		font-weight: 700;
		font-size: 36rpx;
		margin: 0 10rpx;
		user-select: none;
		cursor: pointer;
		transition: background 0.3s ease;
	}

	.titlebia1:hover,
	.titlebia2:hover {
		background: #e68300;
	}

	.image-grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		padding: 10rpx;
		gap: 12rpx;
	}

	.image-item {
		width: 30%;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	.image-item image {
		width: 100%;
		height: 200rpx;
		display: block;
		object-fit: cover;
	}

	.AiImag-typea {
		display: flex;
	}
</style>